package cn.just.controller;

import cn.just.entity.Article;
import cn.just.entity.Link;
import cn.just.entity.Tag;
import cn.just.entity.User;
import cn.just.service.ArticleService;
import cn.just.service.LinkService;
import cn.just.service.TagService;
import cn.just.utils.Page;
import cn.just.utils.THUtils;
import org.thymeleaf.context.Context;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @author wujiaming
 */
@WebServlet(name = "ListServlet",value = "/ListServlet")
public class ListServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Context context = new Context();
        ArticleService articleService = new ArticleService();
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        context.setVariable("userName",user.getUserName());

        //当前页码
        String pageNoStr = request.getParameter("pageNo");
        int pageNo = pageNoStr==null?1:Integer.parseInt(pageNoStr);
        //查询当前页的文章
        List<Article> articleList = articleService.getArticleList(pageNo);
        //查询文章的总数量
        int totalCount = articleService.selectCount();
        //将分页查询的结果封装到page对象中
        Page<Article> page = new Page<Article>();
        page.addAll(articleList);
        page.setValue(pageNo,totalCount,8);
        context.setVariable("articleList",page);


        //查询最新文章列表
        List<Article> newList = articleService.getNewList();
        context.setVariable("newList",newList);

        //查询评论最多的文章
        List<Article> maxCommentArticle = articleService.getMaxCommentArticle();
        context.setVariable("maxCommentArticle",maxCommentArticle);

        //查询评论最多的文章
        List<Article> maxViewArticle = articleService.getMaxViewArticle();
        context.setVariable("maxViewArticle",maxViewArticle);

        //查询标签没引用对多的
        TagService tagService = new TagService();
        List<Tag> tags = tagService.findTagByreferenceCount();
        context.setVariable("tags",tags);

        //友情链接,查询所有的链接名称和地址
        LinkService linkService = new LinkService();
        List<Link> links = linkService.findAll();
        context.setVariable("links",links);

        THUtils.write("blog/list",context,response);
    }
}
